#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "encrypt.h"
#include "decrypt.h"
#include "utils.h"

void print_usage(const char *prog_name) {
    fprintf(stderr, "Usage: %s --encrypt|--decrypt --input <file> --output <file> --password <pass>\n", prog_name);
}

int main(int argc, char *argv[]) {
    int opt;
    int encrypt_flag = 0, decrypt_flag = 0;
    const char *input_path = NULL;
    const char *output_path = NULL;
    const char *password = NULL;

    while ((opt = getopt(argc, argv, "edhi:o:p:")) != -1) {
        switch (opt) {
            case 'e':
                encrypt_flag = 1;
                break;
            case 'd':
                decrypt_flag = 1;
                break;
            case 'i':
                input_path = optarg;
                break;
            case 'o':
                output_path = optarg;
                break;
            case 'p':
                password = optarg;
                break;
            case 'h':
            default:
                print_usage(argv[0]);
                return 1;
        }
    }

    if (!(encrypt_flag ^ decrypt_flag) || !input_path || !output_path || !password) {
        print_usage(argv[0]);
        return 1;
    }

    CipherContext *ctx = create_cipher_context(password);
    if (!ctx) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    if (encrypt_flag) {
        if (encrypt_file(input_path, output_path, ctx) != 0) {
            fprintf(stderr, "Encryption failed\n");
            free_cipher_context(ctx);
            return 1;
        }
        printf("Encryption completed, output file: %s\n", output_path);
    } else if (decrypt_flag) {
        if (decrypt_file(input_path, output_path, ctx) != 0) {
            fprintf(stderr, "Decryption failed\n");
            free_cipher_context(ctx);
            return 1;
        }
        printf("Decryption completed, output file: %s\n", output_path);
    }

    free_cipher_context(ctx);
    return 0;
}